<script setup lang="ts">
import {type AuthType, useModalStore, useThirdStore, useUserStore} from "@/stores";
import {computed, onBeforeMount, reactive, ref, unref} from "vue";
import api from "@/api";
import dayjs from "dayjs";
import {uuid} from "@/utils/random";
import clickCaptcha from "@/components/clickCaptcha/sum-click-captcha.vue";
import type {getSessionIdResType} from "@/types/third";

const mobileRule = {
  rules: [
    {
      required: true,
      errorMessage: '请输入手机号',
    },
    {
      validateFunction: function (rule, value, data, callback) {
        if(!/^1[3-9]\d{9}$/.test(value)){
          callback('请输入正确的手机号');
        }
        return true;
      },
    },
  ],
};
const password = {
  rules: [
    {
      required: true,
      errorMessage: '请输入密码',
    },
    {
      validateFunction: function (rule, value, data, callback) {
        if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+\S{5,12}$/.test(value)) {
          callback('需包含字母和数字,长度在6-12之间');
        }
        return true;
      },
    },
  ],
};


const modalStore = useModalStore();
const authType = computed(() => modalStore.auth);
const closeAuthModal = () => {
  modalStore.setAuth(null);
}

const onChangeMobile = () => {
  modalStore.setAuth('changeMobile');
}

const userStore = useUserStore();

// 表单引用
const uFormRef = ref(null);

const form = reactive({
  avatar_url: userStore.userInfo?.avatar_url,
  avatar: userStore.userInfo?.avatar,
  nickname: userStore.userInfo?.nickname,
  mobile: userStore.userInfo?.mobile,
  gender: userStore.userInfo?.gender,
  birthday: userStore.userInfo?.birthday,
})
const onChooseAvatar = (e:any) => {
  const tempUrl = e.detail.avatarUrl || '';
  uploadAvatar(tempUrl);
}
// 修改头像
const onChangeAvatar = () => {
  uni.chooseImage({
    success: async (chooseImageRes) => {
      const tempUrl = chooseImageRes.tempFilePaths[0];
      uploadAvatar(tempUrl);
    },
  })
}

const uploadAvatar = async (tempUrl:any) => {
  if (!tempUrl) return;
  const { code,data } = await api.common.uploadApi(tempUrl)
  if (code === 1) {
    form.avatar_url = data.file.full_url;
    form.avatar = data.file.url;
  }
  console.log(form)
}

const onSubmit = async () => {
  const { code,data } = await api.user.updateApi({
    avatar: form.avatar,
    nickname: form.nickname,
    gender: form.gender,
  });
  if (code == 1) {
    userStore.setUserInfo(data);
  }
}

// 基本案列数据
const radiolist1 = reactive([
  {
    name: '保密',
    val: 0,
    disabled: false,
  },
  {
    name: '男',
    val: 1,
    disabled: false,
  },
  {
    name: '女',
    val: 2,
    disabled: false,
  },])

const radiovalue1 = ref(0);

const radioChange = (n) => {
  console.log('radioChange', n);
};

onBeforeMount(async ()=>{
  await updateUserData();
})

const updateUserData =async ()=>{
  if(!userStore.userToken){
    return false;
  }
  const {code,data} =await api.user.profileApi();
  if(code === 1){
    userStore.setUserInfo(data.userInfo);
    // 按变量赋值到form
    Object.assign(form,data.userInfo);
  }
}

const placeholderStyle = 'color:#BBBBBB;font-size:28rpx;line-height:normal';

/*手机绑定相关*/
const changeMobileRef = ref(null);
const changeMobileState= reactive({
  captchaId: uuid(),
  captchaInfo: '',
  showClickCaptcha:false,
  callbackClickCaptcha: (res) => {
    changeMobileState.captchaInfo = res.captchaInfo;
    getSmsCodeTrue('changeMobile')
  },
  lastSendTimer: 0, // 最后一次发送验证码的时间
  isMobileEnd: false, // 手机号输入完毕
  model: {
    mobile: '', // 手机号
    code: '', // 验证码
  },
  rules: {
    mobile:mobileRule,
    code: {
      rules: [
        {
          required: true,
          errorMessage: '请输入验证码',
        },
      ],
    },
  },
});
const getSmsTimer = (event:string):string => {
  const duration = ref(dayjs().unix() - changeMobileState.lastSendTimer - 60);
  const canSend = duration.value >= 0;

  if (canSend) {
    return '获取验证码';
  }
  if (!canSend) {
    setTimeout(() => {
      duration.value++;
    }, 1000);
    return -duration.value.toString() + ' 秒';
  }
}

const getSmsCode =(event:string,mobile:string) => {
  const duration = dayjs().unix() - changeMobileState.lastSendTimer;
  const canSend = duration >= 60;
  if (!canSend) {
    uni.showToast({
      title: '请稍后再试',
      icon: 'none',
    })
    return;
  }
  // 手机号验证
  if(!/^1[3-9]\d{9}$/.test(mobile)){
    uni.showToast({
      title: '手机号格式不正确',
      icon: 'none',
    })
    return;
  }
  changeMobileState.showClickCaptcha=true;
}
const getSmsCodeTrue = async (event:string) => {
 const {code}=await api.common.smsSendApi({
    mobile: changeMobileState.model.mobile,
    template_code: 'user_change_mobile',
    captchaId: changeMobileState.captchaId,
    captchaInfo: changeMobileState.captchaInfo,
  })
  if(code === 1){
    //倒计时
    changeMobileState.lastSendTimer = dayjs().unix();
  }

}

const changeMobileSubmit=async ()=>{
  // const validate =await unref(changeMobileRef)
  //     .validate()
  //     .catch((err)=>{
  //      console.log(err)
  //     })
  // if(!validate)return;
  const {code,data} = await api.user.changeMobileApi({
    mobile: changeMobileState.model.mobile,
    captcha: changeMobileState.model.code,
  })
  if(code === 1){
    updateUserData();
    closeAuthModal();
  }
}
const thirdStore = useThirdStore();
const getSessionId = async (auto_login = null) => {
  // 检查是否有session_id
  if (thirdStore.sessionId) {
    return true;
  }
  // 获取code
  let codeStr = '';
  const loginResult = await uni.login();
  console.log('loginResult', loginResult)
  if (loginResult.errMsg === 'login:ok') {
    codeStr = loginResult.code;
  } else {
    return false;
  }
  await api.third.getSessionIdApi({
    platform: 'miniApp',
    payload: encodeURIComponent(JSON.stringify({
      code: codeStr,
      auto_login
    }))
  }).then((res: ApiResponse<getSessionIdResType>) => {
    if (res.code == 1) {
      thirdStore.setSessionId(res.data.session_id)
      return true;
    }
    return false;
  })
}

const getPhoneNumber=async (e)=>{
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    return false;
  }else{
    await getSessionId();
    const {code}=await api.third.bindUserPhoneNumberApi({
      platform: 'miniApp',
      payload: encodeURIComponent(JSON.stringify({
        sessionId: thirdStore.sessionId,
        iv:e.detail.iv,
        encryptedData:e.detail.encryptedData,
        code:e.detail.code
      }))
    })
    if(code===1){
      updateUserData();
      closeAuthModal();
    }
  }
}

/*修改密码相关*/

const onSetPassword = () => {
  modalStore.setAuth('changePassword');

}



const changePasswordRef = ref(null);
// 数据
const changePassworState = reactive({
  isMobileEnd: false, // 手机号输入完毕
  model: {
    oldPassword: '', //旧密码
    newPassword: '', //新密码
    reNewPassword: '', //确认密码
  },
  rules: {
    oldPassword: password,
    newPassword: password,
    reNewPassword: {
      rules: [
        {
          required: true,
          errorMessage: '请确认密码',
        },
        {
          validateFunction: function (rule, value, data, callback) {
            if (value !== changePassworState.model.newPassword) {
              callback('两次输入的密码不一致');
            }
            if (value === changePassworState.model.oldPassword) {
              callback('新密码不能与旧密码相同');
            }
            return true;
          },
        },
      ],
    },
  },
});

const changePasswordSubmit=async ()=>{
  const validate =await unref(changePasswordRef)
      .validate()
      .catch((error) => {
        console.log('error: ', error);
      });
  if (!validate) return;
  const {code}= await api.user.changePasswordApi(changePassworState.model)
  if(code === 1){
    closeAuthModal();
  }
}


const showAuthModal = (type:AuthType) => {
  if(authType !== null){
    closeAuthModal();
    setTimeout(()=>{
      modalStore.setAuth(type);
    },100)
  }else{
    modalStore.setAuth(type);
  }
}

/*忘记密码相关*/
const getSmsTimerRp = (event:string):string => {
  const duration = ref(dayjs().unix() - resetPasswordState.lastSendTimer - 60);
  const canSend = duration.value >= 0;

  if (canSend) {
    return '获取验证码';
  }
  if (!canSend) {
    setTimeout(() => {
      duration.value++;
    }, 1000);
    return -duration.value.toString() + ' 秒';
  }
}
const getSmsCodeRp =(event:string,mobile:string) => {
  const duration = dayjs().unix() - resetPasswordState.lastSendTimer;
  const canSend = duration >= 60;
  if (!canSend) {
    uni.showToast({
      title: '请稍后再试',
      icon: 'none',
    })
    return;
  }
  // 手机号验证
  if(!/^1[3-9]\d{9}$/.test(mobile)){
    uni.showToast({
      title: '手机号格式不正确',
      icon: 'none',
    })
    return;
  }
  resetPasswordState.showClickCaptcha=true;
}
const getSmsCodeTrueRp = async (event:string) => {
  const {code}=await api.common.smsSendApi({
    mobile: resetPasswordState.model.mobile,
    template_code: 'user_retrieve_pwd',
    captchaId: resetPasswordState.captchaId,
    captchaInfo: resetPasswordState.captchaInfo,
  })
  if(code === 1){
    //倒计时
    resetPasswordState.lastSendTimer = dayjs().unix();
  }

}
const resetPasswordRef = ref(null);

// 数据
const resetPasswordState = reactive({
  captchaId: uuid(),
  captchaInfo: '',
  showClickCaptcha:false,
  callbackClickCaptcha: (res) => {
    resetPasswordState.captchaInfo = res.captchaInfo;
    getSmsCodeTrueRp('resetPassword')
  },
  lastSendTimer: 0, // 最后一次发送验证码的时间
  isMobileEnd: false, // 手机号输入完毕
  model: {
    mobile: '', //手机号
    code: '', //验证码
    password: '', //密码
  },
  rules: {
    code: {
      rules: [
        {
          required: true,
          errorMessage: '请输入验证码',
        },
      ],
    },
    mobile:mobileRule,
    password,
  },
});
const resetPasswordSubmit=async ()=>{
  const validate =await unref(resetPasswordRef)
     .validate()
     .catch((error) => {
        console.log('error: ', error);
      });
  if (!validate) return;
  const {code}= await api.user.resetPasswordApi({
    mobile: resetPasswordState.model.mobile,
    captcha: resetPasswordState.model.code,
    password: resetPasswordState.model.password,
  })
  if(code === 1){
    closeAuthModal();
  }
}

const goLogin=()=>{
  closeAuthModal();
  uni.navigateTo({
    url:'/pages/login/index'
  })
}

</script>

<template>
  <view class="container">

    <view class="avatar">
      <view class="header-box-content">
        <image :src="form.avatar_url ? form.avatar_url : '/static/images/mine/default.png'" style="width:160rpx;height:160rpx"></image>
        <view class="avatar-action">
          <!-- #ifdef MP -->
          <button
              class="ss-reset-button avatar-action-btn"
              open-type="chooseAvatar"
              @chooseavatar="onChooseAvatar"
          >修改</button
          >
          <!-- #endif -->
          <!-- #ifndef MP -->
          <button class="ss-reset-button avatar-action-btn" @tap="onChangeAvatar">修改</button>
          <!-- #endif -->
        </view>
      </view>
    </view>

    <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
    <up-form labelPosition="left" :model="form" ref="uFormRef" :border-bottom="true" class="form"
             labelWidth="150rpx" labelAlign="left">

      <up-form-item label="昵称" prop="form.nickname" :border-bottom="true">
        <uni-easyinput
            v-model="form.nickname"
            type="nickname"
            placeholder="设置昵称"
            :inputBorder="false"
            :placeholderStyle="placeholderStyle"
            primaryColor="#f9ae3d"
            style="text-align: right"
        />
        <template #right>
          <up-icon
              name="arrow-right"
          ></up-icon>
        </template>
      </up-form-item>

      <up-form-item label="手机号码" prop="form.mobile" :border-bottom="true" ref="item1" @tap="onChangeMobile">
        <up-input v-model="form.mobile" disabled disabledColor="#fff" inputAlign="right" placeholder="请绑定手机号" border="none"></up-input>
        <template #right>
          <up-icon
              name="arrow-right"
          ></up-icon>
        </template>
      </up-form-item>

      <up-form-item label="登录密码" prop="form.name" :border-bottom="true" ref="item1" @tap="onSetPassword">
        <up-input disabled
                  disabledColor="#fff"  type="password" inputAlign="right"
                  :placeholder="userStore.userInfo?.verification?.password ? '修改登录密码' : '点击设置登录密码'"
                  border="none"
        ></up-input>
        <template #right>
          <up-icon
              name="arrow-right"
          ></up-icon>
        </template>
      </up-form-item>

      <up-form-item label="性别" prop="form.sex" :border-bottom="true">
        <up-radio-group v-model="form.gender" placement="column" class="u-flex">
          <up-radio :customStyle="{ marginBottom: '8px' }" v-for="(item, index) in radiolist1" :key="index"
                    :label="item.name" :name="item.val" @change="radioChange" activeColor="#f0ad4e"
                    class="radio-box">
          </up-radio>
        </up-radio-group>
      </up-form-item>
    </up-form>


    <view class="footer">
      <up-button @click="onSubmit" type="warning" shape="circle">保存</up-button>
    </view>
  </view>
  <view>
    <up-popup :show="authType !== null" :round="10" mode="bottom" @close="closeAuthModal">
      <view v-if="authType==='changeMobile'" class="login-wrap">
        <view class="head-box ss-m-b-60">
          <view class="head-title ss-m-b-20">
            {{ userStore.userInfo?.verification?.mobile ? '更换手机号' : '绑定手机号' }}
          </view>
          <view class="head-subtitle">为了您的账号安全，请使用本人手机号码</view>
        </view>
        <!-- 表单项 -->
        <uni-forms
            ref="changeMobileRef"
            v-model="changeMobileState.model"
            :rules="changeMobileState.rules"
            validateTrigger="bind"
            labelWidth="140"
            labelAlign="center"
        >
          <uni-forms-item name="mobile" label="手机号">
            <uni-easyinput
                placeholder="请输入手机号"
                v-model="changeMobileState.model.mobile"
                :inputBorder="false"
                type="number"
            >
              <template v-slot:right>
                <button
                    class="ss-reset-button code-btn-start"
                    :disabled="changeMobileState.isMobileEnd"
                    :class="{ 'code-btn-end': changeMobileState.isMobileEnd }"
                    @tap="getSmsCode('changeMobile',changeMobileState.model.mobile)"
                >
                  {{ getSmsTimer('changeMobile') }}
                </button>
              </template>
            </uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="code" label="验证码">
            <uni-easyinput
                placeholder="请输入验证码"
                v-model="changeMobileState.model.code"
                :inputBorder="false"
                type="number"
                maxlength="4"
            >
              <template v-slot:right>
                <button class="ss-reset-button login-btn-start" @tap="changeMobileSubmit">
                  确认
                </button>
              </template>
            </uni-easyinput>
          </uni-forms-item>
        </uni-forms>
        <!--#ifdef MP-->
        <button
            class="ss-reset-button type-btn"
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
        >
          使用微信手机号
        </button>
        <!--#endif-->
        <click-captcha v-if="changeMobileState.showClickCaptcha" :uuid="changeMobileState.captchaId" v-model="changeMobileState.showClickCaptcha" @callback="changeMobileState.callbackClickCaptcha"></click-captcha>

      </view>
      <view v-if="authType==='changePassword'" class="login-wrap">
        <!-- 标题栏 -->
        <view class="head-box ss-m-b-60">
          <view class="head-title ss-m-b-20">修改密码</view>
          <view class="head-subtitle">如密码丢失或未设置,请点击忘记密码重新设置</view>
        </view>
        <!-- 表单项 -->
        <uni-forms
            ref="changePasswordRef"
            v-model="changePassworState.model"
            :rules="changePassworState.rules"
            validateTrigger="bind"
            labelWidth="140"
            labelAlign="center"
        >
          <uni-forms-item name="oldPassword" label="旧密码">
            <uni-easyinput
                placeholder="请输入旧密码"
                v-model="changePassworState.model.oldPassword"
                type="text"
                :inputBorder="false"
            />
          </uni-forms-item>

          <uni-forms-item name="newPassword" label="新密码">
            <uni-easyinput
                type="password"
                placeholder="请输入新密码"
                v-model="changePassworState.model.newPassword"
                :inputBorder="false"
            />
          </uni-forms-item>

          <uni-forms-item name="reNewPassword" label="确认密码">
            <uni-easyinput
                type="password"
                placeholder="请重新输入您的新密码"
                v-model="changePassworState.model.reNewPassword"
                :inputBorder="false"
            >
              <template v-slot:right>
                <button class="ss-reset-button login-btn-start" @tap="changePasswordSubmit">
                  确认
                </button>
              </template>
            </uni-easyinput>
          </uni-forms-item>
        </uni-forms>

        <view class="editPwd-btn-box ss-m-t-80">
          <button class="ss-reset-button forgot-btn" @tap="showAuthModal('resetPassword')">
            忘记密码
          </button>
        </view>
      </view>
      <view v-if="authType==='resetPassword'" class="login-wrap">
        <!-- 标题栏 -->
        <view class="head-box ss-m-b-60">
          <view class="head-title ss-m-b-20">重置密码</view>
          <view class="head-subtitle">为了您的账号安全，设置密码前请先进行安全验证</view>
        </view>
        <!-- 表单项 -->
        <uni-forms
            ref="resetPasswordRef"
            v-model="resetPasswordState.model"
            :rules="resetPasswordState.rules"
            validateTrigger="bind"
            labelWidth="140"
            labelAlign="center"
        >
          <uni-forms-item name="mobile" label="手机号">
            <uni-easyinput
                placeholder="请输入手机号"
                v-model="resetPasswordState.model.mobile"
                type="number"
                :inputBorder="false"
            >
              <template v-slot:right>
                <button
                    class="ss-reset-button code-btn code-btn-start"
                    :disabled="resetPasswordState.isMobileEnd"
                    :class="{ 'code-btn-end': resetPasswordState.isMobileEnd }"
                    @tap="getSmsCodeRp('resetPassword', resetPasswordState.model.mobile)"
                >
                  {{ getSmsTimerRp('resetPassword') }}
                </button>
              </template>
            </uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="code" label="验证码">
            <uni-easyinput
                placeholder="请输入验证码"
                v-model="resetPasswordState.model.code"
                type="number"
                maxlength="4"
                :inputBorder="false"
            ></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="password" label="密码">
            <uni-easyinput
                type="password"
                placeholder="请输入密码"
                v-model="resetPasswordState.model.password"
                :inputBorder="false"
            >
              <template v-slot:right>
                <button class="ss-reset-button login-btn-start" @tap="resetPasswordSubmit">
                  确认
                </button>
              </template>
            </uni-easyinput>
          </uni-forms-item>
        </uni-forms>

        <button class="ss-reset-button type-btn" @tap="goLogin">
          返回登录
        </button>
        <click-captcha v-if="resetPasswordState.showClickCaptcha" :uuid="resetPasswordState.captchaId" v-model="resetPasswordState.showClickCaptcha" @callback="resetPasswordState.callbackClickCaptcha"></click-captcha>

      </view>
    </up-popup>
  </view>
</template>

<style lang="scss" scoped>
.container {
  .u-flex {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
  }

  .radio-box {
    margin-right: 20rpx;
  }
  .form {
    padding: 30rpx;
    background: #fff;
  }

  .footer {
    margin-top: 50rpx;
    padding: 20rpx 60rpx;
  }
  .avatar {
    background: #fff;
    padding-top: 30rpx;
    padding-bottom: 20rpx;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
  .header-box-content {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    overflow: hidden;
    border-radius: 50%;
  }
  .avatar-action {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 0;
    z-index: 1;
    width: 160rpx;
    height: 46rpx;
    background: rgba(#000000, 0.3);
    .avatar-action-btn {
      width: 160rpx;
      height: 46rpx;
      font-weight: 500;
      font-size: 24rpx;
      color: #ffffff;
    }
  }
}
/* ==================
    按钮
 ==================== */
.ss-reset-button {
  padding: 0;
  margin: 0;
  font-size: inherit;
  background-color: transparent;
  color: inherit;
  position: relative;
  border: 0rpx;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  text-align: center;
  text-decoration: none;
  white-space: nowrap;
  vertical-align: baseline;
  transform: translate(0, 0);
}
.ss-reset-button.button-hover {
  transform: translate(1px, 1px);
  background: none;
}

.ss-reset-button::after {
  border: none;
}

.code-btn-start {
  width: 160rpx;
  height: 56rpx;
  line-height: normal;
  border: 2rpx solid #ff6000;
  border-radius: 28rpx;
  font-size: 26rpx;
  font-weight: 400;
  color: #ff6000;
  opacity: 1;
}

.login-btn-start {
  width: 158rpx;
  height: 56rpx;
  line-height: normal;
  background: linear-gradient(90deg, #ff6000, rgba(255, 96, 0, .6));
  border-radius: 28rpx;
  font-size: 26rpx;
  font-weight: 500;
  color: #fff;
}

.login-wrap {
  padding: 50rpx 34rpx;
  min-height: 500rpx;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
}

.head-box {
  .head-title {
    min-width: 160rpx;
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
    line-height: 36rpx;
  }
  .head-title-active {
    width: 160rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #999;
    line-height: 36rpx;
  }
  .head-title-animation {
    animation-name: title-animation;
    animation-duration: 0.1s;
    animation-timing-function: ease-out;
    animation-fill-mode: forwards;
  }
  .head-title-line {
    position: relative;
    &::before {
      content: '';
      width: 1rpx;
      height: 34rpx;
      background-color: #e4e7ed;
      position: absolute;
      left: -30rpx;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .head-subtitle {
    font-size: 26rpx;
    font-weight: 400;
    color: #afb6c0;
    text-align: left;
    display: flex;
  }
}

.ss-m-b-60 {
  margin-bottom: 1.875rem
}
.ss-m-b-20 {
  margin-bottom: .625rem
}

</style>